package com.java.string.StringBuilder.source_analyze;

import com.java.string.StringBuilder.source_analyze.source_code.StringBuilder;

public class Main {
    public static void main(String[] args) {
        // 默认初始容量为16
        StringBuilder stringBuilder1 = new StringBuilder();
        
        // 字符串为空，则新增字符串"null"
        stringBuilder1.append(null);
        System.out.println(stringBuilder1); // null
        System.out.println(stringBuilder1.capacity()); // 16
        
        // 原容量能存下新添加的元素，则无需扩容直接存
        stringBuilder1.append("123456789");
        System.out.println(stringBuilder1); // null123456789
        System.out.println(stringBuilder1.capacity()); // 16
        
        // 改变判断条件查看不同结果
        if (true) {
            // 原容量无法存下新添加的元素但根据(原容量*2+2)求得的扩容容量能存下新添加的元素，则扩容为(原容量*2+2)后存
            stringBuilder1.append("abcdefg");
            System.out.println(stringBuilder1); // null123456789abcdefg
            System.out.println(stringBuilder1.capacity()); // 34
        } else {
            // 原容量无法存下新添加的元素且根据(原容量*2+2)求得的扩容容量也无法存下新添加的元素，则扩容为加上新增加元素后的实际容量存
            stringBuilder1.append("abcdefghijklmnopqrstuvwxyz");
            System.out.println(stringBuilder1); // null123456789abcdefghijklmnopqrstuvwxyz
            System.out.println(stringBuilder1.capacity()); // 39
        }
        
        // 构造函数指定容量时则为指定容量
        StringBuilder stringBuilder2 = new StringBuilder(2);
        System.out.println(stringBuilder2.capacity()); // 2
        stringBuilder2.append("123");
        System.out.println(stringBuilder2); // 123
        System.out.println(stringBuilder2.capacity()); // 6
        
        // 构造函数指定字符串时则为`16+字符串长度`
        StringBuilder stringBuilder3 = new StringBuilder("1234");
        System.out.println(stringBuilder3); // 1234
        System.out.println(stringBuilder3.capacity()); // 20
    }
}
